package com.th.cash.th2.splash

import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.LogLevel
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.utils.CommUtils
import com.th.cash.application.MyApplication
import com.th.cash.th2.main.ProductApplyRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.debounce

class SplashViewModel : BaseViewModel() {

    private val repository by lazy {
        SplashRepository()
    }

    val intentChannel = Channel<SplashIntent>(Channel.UNLIMITED)

    //可变状态数据流（读写）（StateFlow替代LiveData，难道每一个页面都需要定义一个）
    private val _uiState = MutableStateFlow<SplashState>(SplashState.Idle)

    //可观察状态数据流（只读）
    val uiState: StateFlow<SplashState> get() = _uiState

    init {
        viewModelScope.launch {
            intentChannel.consumeAsFlow().debounce(500).collect { value ->
                when (value) {
                    is SplashIntent.Idle -> {
                        getGoogleMarket()
                    }

                    else -> {
                    }
                }
            }
        }
    }

    private fun getGoogleMarket() {
        GlobalScope.launch(Dispatchers.IO) {
            val result = repository.getGoogleMarket()
            result.checkResult(success = {

                it?.let {
                    initAdjust(it)
                }

            }, error = {
                loadError(it)
            })
        }
    }

    private fun initAdjust(request: AdjustRequest) {
        if (request.wqyGWTgDoomfulEmHkUqx == 0) {
            return
        }

        val environment = AdjustConfig.ENVIRONMENT_PRODUCTION
        val config = AdjustConfig(CommUtils.getContext(), request.RfGwHMjNhgQHtRsgk, environment)
        config.setLogLevel(LogLevel.VERBOSE)//设置日志级别
        config.enableSendingInBackground()
        if (!TextUtils.isEmpty(request.xbygDEEProcuratorshipFQTYBQl)) {
            config.fbAppId = request.xbygDEEProcuratorshipFQTYBQl
        }

        Adjust.initSdk(config)

    }

}